package queue

import (
	"context"
	"github.com/gogf/gf/container/gmap"
	"github.com/gogf/gf/os/gcfg"
	"github.com/thoas/bokchoy"
)

var (
	Ctx         context.Context
	Engine      *bokchoy.Bokchoy
	Request     *bokchoy.Request
	instances   = gmap.NewStrAnyMap(true)
	DefaultName = "queue"
)

func New() *bokchoy.Bokchoy {
	ctx := context.Background()

	// define the main engine which will manage queues
	engine, err := bokchoy.New(ctx, bokchoy.Config{
		Broker: bokchoy.BrokerConfig{
			Type: gcfg.Instance().GetString("queue.driver"),
			Redis: bokchoy.RedisConfig{
				Type: "client",
				Client: bokchoy.RedisClientConfig{
					Addr: gcfg.Instance().GetString("queue.addr"),
				},
			},
		},
	})
	if err != nil {
		panic(err)
	}
	Engine = engine
	Ctx = ctx
	return engine
}

// 容器封装
func Instance(name ...string) *bokchoy.Bokchoy {
	key := DefaultName
	if len(name) > 0 && name[0] != "" {
		key = name[0]
	}
	return instances.GetOrSetFuncLock(key, func() interface{} {
		return New()
	}).(*bokchoy.Bokchoy)
}

// 客户端示例
func Client(name ...string) *bokchoy.Bokchoy {
	return Instance(name...)
}

// 发布
func Publish(name string, data interface{}) {
	_, err := Client().Queue(name).Publish(Ctx, data)
	if err != nil {
		panic(err)
	}
}